import React, { useState, useRef } from 'react';
import ReactCrop, { Crop, PixelCrop } from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
import { useTranslation } from 'react-i18next';
import { request } from '@/api/request';
import { message } from 'antd';

interface AvatarUploadModalProps {
    open: boolean;
    onClose: () => void;
    onSuccess: () => void;
    currentAvatar?: string;
}

const AvatarUploadModal: React.FC<AvatarUploadModalProps> = ({
    open,
    onClose,
    onSuccess,
    currentAvatar
}) => {
    const { t } = useTranslation();
    const [selectedImage, setSelectedImage] = useState<string | null>(null);
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    const [showCrop, setShowCrop] = useState(false);
    const [crop, setCrop] = useState<Crop>({
        unit: '%',
        width: 100,
        height: 100,
        x: 0,
        y: 0
    });
    const [completedCrop, setCompletedCrop] = useState<PixelCrop>();
    const [isLoading, setIsLoading] = useState(false);
    const imgRef = useRef<HTMLImageElement>(null);
    const fileInputRef = useRef<HTMLInputElement>(null);

    // 处理文件选择
    const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (file) {
            if (file.size > 5 * 1024 * 1024) { // 5MB限制
                message.error(t('settings.avatarUpload.imageTooLarge'));
                return;
            }

            setSelectedFile(file);
            const reader = new FileReader();
            reader.onload = () => {
                setSelectedImage(reader.result as string);
            };
            reader.readAsDataURL(file);
        }
    };

    // 触发文件选择
    const handleAvatarClick = () => {
        fileInputRef.current?.click();
    };

    // 直接上传原图
    const handleDirectUpload = async () => {
        if (!selectedFile) {
            message.error(t('settings.avatarUpload.noImageSelected'));
            return;
        }

        setIsLoading(true);
        try {
            const formData = new FormData();
            formData.append('avatar', selectedFile);

            const response = await request.post('/api/visitor/updateUserAvatar', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            if (response.data.success) {
                message.success(t('settings.avatarUpload.uploadSuccess'));

                // 更新本地存储的用户头像数据
                try {
                    const userDataStr = localStorage.getItem('userData');
                    if (userDataStr) {
                        const userData = JSON.parse(userDataStr);
                        const newAvatarUrl = response.data.data?.avatar || URL.createObjectURL(selectedFile);
                        userData.user_avatar = newAvatarUrl;
                        localStorage.setItem('userData', JSON.stringify(userData));

                        // 触发用户数据更新事件
                        window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));
                    }
                } catch (error) {
                    // console.error('更新本地用户数据失败:', error);
                    console.error('update local user data failed', error);
                }

                onSuccess();
                handleClose();
            } else {
                message.error(response.data.message || t('settings.avatarUpload.uploadFailed'));
            }
        } catch (error: any) {
            message.error(error?.response?.data?.message || t('settings.avatarUpload.uploadError'));
        } finally {
            setIsLoading(false);
        }
    };

    // 获取裁剪后的图片
    const getCroppedImg = (): Promise<Blob> => {
        return new Promise((resolve, reject) => {
            if (!imgRef.current || !completedCrop) {
                reject(new Error('No image or crop data'));
                return;
            }

            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            if (!ctx) {
                reject(new Error('No 2d context'));
                return;
            }

            const scaleX = imgRef.current.naturalWidth / imgRef.current.width;
            const scaleY = imgRef.current.naturalHeight / imgRef.current.height;

            canvas.width = completedCrop.width;
            canvas.height = completedCrop.height;

            ctx.drawImage(
                imgRef.current,
                completedCrop.x * scaleX,
                completedCrop.y * scaleY,
                completedCrop.width * scaleX,
                completedCrop.height * scaleY,
                0,
                0,
                completedCrop.width,
                completedCrop.height
            );

            canvas.toBlob((blob) => {
                if (blob) {
                    resolve(blob);
                } else {
                    reject(new Error('Canvas to blob failed'));
                }
            }, 'image/jpeg', 0.9);
        });
    };

    // 上传裁剪后的头像
    const handleCropUpload = async () => {
        if (!completedCrop) {
            message.error(t('settings.avatarUpload.pleaseCropFirst'));
            return;
        }

        setIsLoading(true);
        try {
            const croppedImage = await getCroppedImg();

            const formData = new FormData();
            formData.append('avatar', croppedImage, 'avatar.jpg');

            const response = await request.post('/api/visitor/updateUserAvatar', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            if (response.data.success) {
                message.success(t('settings.avatarUpload.uploadSuccess'));

                // 更新本地存储的用户头像数据
                try {
                    const userDataStr = localStorage.getItem('userData');
                    if (userDataStr) {
                        const userData = JSON.parse(userDataStr);
                        const newAvatarUrl = response.data.data?.avatar || URL.createObjectURL(croppedImage);
                        userData.user_avatar = newAvatarUrl;
                        localStorage.setItem('userData', JSON.stringify(userData));

                        // 触发用户数据更新事件
                        window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));
                    }
                } catch (error) {
                    // console.error('更新本地用户数据失败:', error);
                    console.error('update local user data failed', error);
                }

                onSuccess();
                handleClose();
            } else {
                message.error(response.data.message || t('settings.avatarUpload.uploadFailed'));
            }
        } catch (error: any) {
            message.error(error?.response?.data?.message || t('settings.avatarUpload.uploadError'));
        } finally {
            setIsLoading(false);
        }
    };

    // 重置状态
    const handleClose = () => {
        setSelectedImage(null);
        setSelectedFile(null);
        setShowCrop(false);
        setCrop({
            unit: '%',
            width: 100,
            height: 100,
            x: 0,
            y: 0
        });
        setCompletedCrop(undefined);
        onClose();
    };

    if (!open) return null;

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-60 p-2 md:p-4">
            <div className="bg-[rgb(28,25,23)] border border-[rgb(54,54,54)] rounded-2xl w-full max-w-sm md:max-w-md max-h-[95vh] md:max-h-[90vh] overflow-y-auto shadow-2xl p-3 md:p-6 flex flex-col">
                <div className="text-base md:text-lg font-bold mb-3 md:mb-4 text-white tracking-wide flex-shrink-0 flex justify-between items-center">
                    {t('settings.avatarUpload.title')}
                    <button
                        className="text-gray-400 hover:text-white transition-colors focus:outline-none"
                        onClick={handleClose}
                    >
                        <i className="fas fa-times text-lg"></i>
                    </button>
                </div>

                <div className="flex-1 min-h-0">
                    {!selectedImage ? (
                        // 选择图片界面
                        <div className="text-center">
                            <div
                                className="relative w-20 h-20 md:w-24 md:h-24 mx-auto mb-3 md:mb-4 cursor-pointer group"
                                onClick={handleAvatarClick}
                            >
                                <img
                                    className="w-20 h-20 md:w-24 md:h-24 rounded-full object-cover border-2 border-gray-300 group-hover:border-pink-400 transition-colors"
                                    src={currentAvatar || '/assets/user-icons/man-f06d242ecbaa154c05843d8e91f779c41dbef390319247606b1919b87169c74a.svg'}
                                    alt="Avatar"
                                />
                                <div className="absolute inset-0 bg-black bg-opacity-50 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                    <i className="fas fa-camera text-white text-base md:text-lg"></i>
                                </div>
                            </div>
                            <p className="text-gray-300 mb-3 md:mb-4 text-xs md:text-sm">
                                {t('settings.avatarUpload.clickToSelectImage')}
                            </p>
                            <input
                                ref={fileInputRef}
                                type="file"
                                accept="image/*"
                                onChange={handleFileSelect}
                                className="hidden"
                            />
                        </div>
                    ) : !showCrop ? (
                        // 图片预览和操作界面
                        <div className="space-y-3 md:space-y-4 h-full flex flex-col">
                            {/* 图片预览 */}
                            <div className="flex justify-center">
                                <img
                                    src={selectedImage}
                                    alt="Preview"
                                    className="w-20 h-20 md:w-24 md:h-24 rounded-full object-cover border-2 border-gray-300"
                                />
                            </div>

                            {/* 按钮区域 */}
                            <div className="flex flex-col gap-2 md:gap-3 flex-shrink-0">
                                <button
                                    className={`w-full px-3 md:px-4 py-2 rounded-xl text-white font-bold transition text-xs md:text-sm ${isLoading
                                        ? 'bg-gray-500 cursor-not-allowed'
                                        : 'bg-[rgb(231,82,117)] hover:opacity-90'
                                        }`}
                                    onClick={handleDirectUpload}
                                    disabled={isLoading}
                                >
                                    {isLoading ? (
                                        <div className="flex items-center justify-center">
                                            <div className="animate-spin rounded-full h-3 w-3 md:h-4 md:w-4 border-b-2 border-white mr-1 md:mr-2"></div>
                                            <span className="text-xs md:text-sm">{t('common.uploading')}</span>
                                        </div>
                                    ) : (
                                        t('settings.avatarUpload.uploadDirectly')
                                    )}
                                </button>
                                <button
                                    className="w-full px-3 md:px-4 py-2 rounded-xl bg-gray-600 text-white font-bold hover:bg-gray-700 transition text-xs md:text-sm"
                                    onClick={() => setShowCrop(true)}
                                >
                                    {t('settings.avatarUpload.cropAndUpload')}
                                </button>
                                <button
                                    className="w-full px-3 md:px-4 py-2 rounded-xl bg-gray-600 text-white font-bold hover:bg-gray-700 transition text-xs md:text-sm"
                                    onClick={() => setSelectedImage(null)}
                                >
                                    {t('settings.avatarUpload.reselect')}
                                </button>
                            </div>
                        </div>
                    ) : (
                        // 裁剪界面
                        <div className="space-y-3 md:space-y-4 h-full flex flex-col">
                            {/* 标题  */}
                            <div className="text-xs md:text-sm text-gray-300 mb-2 flex-shrink-0">
                                {t('settings.avatarUpload.cropImage')}
                            </div>

                            {/* 裁剪区域 - 使用flex-1确保占用剩余空间 */}
                            <div className="flex-1 min-h-0 flex justify-center items-center">
                                <div className="w-full max-w-[250px] md:max-w-xs">
                                    <ReactCrop
                                        crop={crop}
                                        onChange={(c) => setCrop(c)}
                                        onComplete={(c) => setCompletedCrop(c)}
                                        circularCrop
                                        ruleOfThirds={false}
                                    >
                                        <img
                                            ref={imgRef}
                                            src={selectedImage}
                                            alt="Crop preview"
                                            className="w-full h-auto max-h-32 md:max-h-48 object-contain"
                                        />
                                    </ReactCrop>
                                </div>
                            </div>

                            {/* 按钮区域 - 固定在底部 */}
                            <div className="flex flex-col sm:flex-row gap-2 md:gap-3 flex-shrink-0">
                                <button
                                    className="w-full sm:flex-1 px-3 md:px-4 py-2 rounded-xl bg-gray-600 text-white font-bold hover:bg-gray-700 transition text-xs md:text-sm"
                                    onClick={() => setShowCrop(false)}
                                >
                                    {t('settings.avatarUpload.back')}
                                </button>
                                <button
                                    className={`w-full sm:flex-1 px-3 md:px-4 py-2 rounded-xl text-white font-bold transition text-xs md:text-sm ${isLoading
                                        ? 'bg-gray-500 cursor-not-allowed'
                                        : 'bg-[rgb(231,82,117)] hover:opacity-90'
                                        }`}
                                    onClick={handleCropUpload}
                                    disabled={isLoading}
                                >
                                    {isLoading ? (
                                        <div className="flex items-center justify-center">
                                            <div className="animate-spin rounded-full h-3 w-3 md:h-4 md:w-4 border-b-2 border-white mr-1 md:mr-2"></div>
                                            <span className="text-xs md:text-sm">{t('common.uploading')}</span>
                                        </div>
                                    ) : (
                                        t('settings.avatarUpload.confirmUpload')
                                    )}
                                </button>
                            </div>
                        </div>
                    )}
                </div>


            </div>
        </div>
    );
};

export default AvatarUploadModal; 